/**
 * 部门机构服务类
 * @author EchoHu
 * contract:elyzium_wow@hotmail.com
 */
package com.pms.privilege.dept.service;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pms.privilege.dept.dao.DeptDAO;
import com.pms.privilege.dept.model.DeptModel;
import com.pms.privilege.user.model.UserModel;

@Service
public class DeptService {
	@Autowired
	protected DeptDAO dao;
	/**
	 * 查询所有部门节点
	 * @return 部门列表
	 */
	public DeptModel queryDeptInfo(long dept_id){
		DeptModel dm=new DeptModel();
		dm=dao.queryDeptById(dept_id);
		return dm;
		
	}
	
	/**
	 * 查询部门树
	 */
	public JSONArray queryDeptTree(long dept_spr){
		JSONArray deptTree=new JSONArray();
		List<DeptModel> list=new ArrayList<DeptModel>();
		list=dao.queryDeptBySpr(dept_spr);
		if(list.size()>0){
			for(DeptModel dm:list){
				JSONObject deptInfo=new JSONObject();
				deptInfo.put("text", dm.getDept_name());
				deptInfo.put("id", dm.getDept_id());
				deptInfo.put("spr", dm.getDept_spr());
				JSONArray node=queryDeptTree(dm.getDept_id());
				if(node.length()>0){
					deptInfo.put("nodes", node);
				}
				deptTree.put(deptInfo);
			}
		}
		return deptTree;
	}
	/**
	 * 新增部门
	 * @param dm
	 * @return
	 */
	public int insertDeptService(DeptModel dm){
		dao.insertDept(dm);
		return 0;
	}
	/**
	 * 删除部门节点
	 * @param dept_id
	 * @return
	 */
	public int deleteDeptService(long dept_id){
		List<DeptModel> list=new ArrayList<DeptModel>();
		list=dao.queryDeptBySpr(dept_id);
		if(list.size()>0){
			for(DeptModel dm:list){
				dao.delUserFromDept(dm.getDept_id());
				deleteDeptService(dm.getDept_id());
			}
			dao.delUserFromDept(dept_id);
			dao.deleteDept(dept_id);
		}else{
			dao.delUserFromDept(dept_id);
			dao.deleteDept(dept_id);
		}
		return 0;
	}
	/**
	 * 获取部门下用户信息列表
	 * @param dept_id
	 * @return
	 */
	public List<UserModel> getUserList(long dept_id){
		List<UserModel> list=new ArrayList<UserModel>();
		list=dao.queryUserByDept(dept_id);
		return list;
		
	}
	
	/**
	 * 添加用户到部门
	 * @param dept_id
	 * @param user_ids
	 * @return
	 */
	public int addUserService(String dept_id,String[] user_ids){
		for(int i=0;i<user_ids.length;i++){
			dao.addUser(Long.parseLong(dept_id), Long.parseLong(user_ids[i]), "d"+dept_id+"u"+user_ids[i]);
		}
		return 0;
		
	}
	
	/**
	 * 删除部门下的用户
	 * @param dept_id
	 * @param user_ids
	 * @return
	 */
	public int delUserService(String dept_id,String[] user_ids){
		for(int i=0;i<user_ids.length;i++){
			dao.delUser(Long.parseLong(dept_id), Long.parseLong(user_ids[i]), "d"+dept_id+"u"+user_ids[i]);
		}
		return 0;
		
	}
}
